﻿namespace S7Cat.Tools
{
    internal class TaskQueue
    {
        private Task previousTask = Task.CompletedTask;

        public async Task Enqueue(Task task)
        {
            var tcs = new TaskCompletionSource();
            await Interlocked.Exchange(ref previousTask, tcs.Task).ConfigureAwait(false);
            try
            {
                await task.ConfigureAwait(false);
            }
            finally
            {
                tcs.SetResult();
            }
        }

        public async Task<T> Enqueue<T>(Task<T> task)
        {
            var tcs = new TaskCompletionSource();
            await Interlocked.Exchange(ref previousTask, tcs.Task).ConfigureAwait(false);
            try
            {
                return await task.ConfigureAwait(false);
            }
            finally
            {
                tcs.SetResult();
            }
        }
    }
}
